/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package beans;

import general.util.EntitiesValidation;
import general.util.MySecurityUtil;
import java.io.Serializable;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import jpa.controller.ObraJpaController;
import jpa.controller.PermissionsJpaController;
import jpa.controller.UserJpaController;
import jpa.entity.Obra;
import jpa.entity.Permissions;
import jpa.entity.User;
import org.primefaces.context.RequestContext;
import org.primefaces.model.DualListModel;

/**
 *
 * @author isaias
 */
@ManagedBean
@ViewScoped
public class UserBean implements Serializable{

    private String passwordCompare;
    private String filterNameUser;
    private User user = new User();
    private User userSelected = new User();
    private DualListModel<Permissions> dualListPermissions = new DualListModel<Permissions>();
    private DualListModel<Obra> dualListObras = new DualListModel<Obra>();

    /** Creates a new instance of UserBean */
    public UserBean() {
        updateGroupPermissions();
        updateOdras();
    }

    public void updateDualList(){
        System.out.println(">>>> updateDualList() name user: "+userSelected.getName());
        updateGroupPermissions();
        updateOdras();
    }

    public void edit(){
       
              List<String> erros = EntitiesValidation.validateUser(userSelected, passwordCompare);

        try {
            if (erros.isEmpty()) {
               
                  userSelected.setObras(dualListObras.getTarget());
                  userSelected.setPermissions(dualListPermissions.getTarget());
               System.out.println(">>>>>>>>> list permissions size: "+userSelected.getPermissions().size());

               for(Permissions p : userSelected.getPermissions()){
                 System.out.println(">>>>>>>>>  id permissions: "+  p.getId());
               }

                new UserJpaController().edit(userSelected);

                userSelected = new User();
                dualListObras = new DualListModel<Obra>();
                dualListPermissions = new DualListModel<Permissions>();
                
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Dados do usuário alterados com sucesso!", null));
                RequestContext.getCurrentInstance().addCallbackParam("showDialog", false);
                return;
            } else {
                for (String erro : erros) {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, erro, null));
                }
            }
        } catch (Exception ex) {

            ex.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro ao tentar editar usuário!", null));
        }

         RequestContext.getCurrentInstance().addCallbackParam("showDialog", true);
    }


    public void save(){
              List<String> erros = EntitiesValidation.validateUser(user, passwordCompare);

        try {
            if (erros.isEmpty()) {
                String realPassword = MySecurityUtil.md5(passwordCompare);

                user.setPassword(realPassword);
                user.setActive(true);

                new UserJpaController().create(user);

                user = new User();

                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Usuário criado com sucesso!", null));
                RequestContext.getCurrentInstance().addCallbackParam("showDialog", false);
                return;
            } else {
                for (String erro : erros) {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, erro, null));
                }
            }
        } catch (Exception ex) {

            ex.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro ao tentar criar usuário!", null));
        }

         RequestContext.getCurrentInstance().addCallbackParam("showDialog", true);
    }
    

    private void updateGroupPermissions() {

        List<Permissions> permissionsDisponiveis = new PermissionsJpaController().findPermissionsEntities();
        List<Permissions> userSelectedPermissions = userSelected.getPermissions();
        permissionsDisponiveis.removeAll(userSelectedPermissions);

        dualListPermissions = new DualListModel<Permissions>(permissionsDisponiveis, userSelectedPermissions);
    }


    private void updateOdras(){
        List<Obra> obrasDisponiveis = new ObraJpaController().findObraEntities();
        List<Obra> userSelectedObras = userSelected.getObras();
        obrasDisponiveis.removeAll(userSelectedObras);

        dualListObras = new DualListModel<Obra>(obrasDisponiveis, userSelectedObras);
    }

    public List<User> getListUsers(){
         return new UserJpaController().findUserAjaxName(filterNameUser);
    }

    public String getFilterNameUser() {
        return filterNameUser;
    }

    public void setFilterNameUser(String filterNameUser) {
        this.filterNameUser = filterNameUser;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public User getUserSelected() {
        return userSelected;
    }

    public void setUserSelected(User userSelected) {
        this.userSelected = userSelected;
    }

    public String getPasswordCompare() {
        return passwordCompare;
    }

    public void setPasswordCompare(String passwordCompare) {
        this.passwordCompare = passwordCompare;
    }

    public DualListModel<Permissions> getDualListPermissions() {
        return dualListPermissions;
    }

    public void setDualListPermissions(DualListModel<Permissions> dualListPermissions) {
        this.dualListPermissions = dualListPermissions;
    }

    public DualListModel<Obra> getDualListObras() {
        return dualListObras;
    }

    public void setDualListObras(DualListModel<Obra> dualListObras) {
        this.dualListObras = dualListObras;
    }
    
}
